package javaweb.sevice.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import javaweb.exception.DeleteException;
import javaweb.mapper.ClazzMapper;
import javaweb.pojo.Clazz;
import javaweb.pojo.ClazzPageResult;
import javaweb.pojo.ClazzQueryParam;
import javaweb.pojo.Emp;
import javaweb.sevice.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/*
* 班级管理业务层
* */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    /*
    * 班级信息分页查询
    * */
    @Override
    public ClazzPageResult getClazzInfo(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        //调用Mapper接口
        List<Clazz> clazzList = clazzMapper.selectClazzInfo(clazzQueryParam);
        if(!CollectionUtils.isEmpty(clazzList)){
            for (Clazz clazz : clazzList) {
                if(clazz.getEndDate().isBefore(LocalDate.now())){
                    clazz.setStatus("已结课");
                }else if(clazz.getBeginDate().isAfter(LocalDate.now())){
                    clazz.setStatus("未开班");
                }else {
                    clazz.setStatus("已开班");
                }
            }
        }
        Page<Clazz> p = (Page<Clazz>) clazzList;

        //封装ClazzPageResult对象
        return new ClazzPageResult(p.getTotal(), p.getResult());
    }

    /*
    * 获取班主任信息
    * */
    @Override
    public List<Emp> getMaster() {
        return clazzMapper.selectMaster();
    }

    /*
    * 添加新班级操作
    * */
    @Override
    public void addClazz(Clazz clazz) {
        //设置基本信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        //调用Mapper接口
        //保存班级信息
        clazzMapper.insertClazz(clazz);

    }

    /*
    * 根据id查询班级信息
    * */
    @Override
    public Clazz getClazzById(Integer id) {
        return clazzMapper.selectClazzById(id);
    }

    /*
    * 修改班级信息
    * */
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    /*
     * 根据id删除班级信息
     * */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void deleteClazzById(Integer id) {
        //查询剩余学生的数量
        Integer num = clazzMapper.countClazzSudent(id);
        if(num > 0) {
            throw new DeleteException();
        }

        //删除班级信息
        clazzMapper.deleteClazzById(id);
    }

}
